#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cstdio>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

#define N 2
#define M 1024

void Write(int wfd)
{
    string s = "I am a child process!";
    pid_t self = getpid();
    int number = 0;
    char buffer[M];
    while (1)
    {
        sleep(1);
        snprintf(buffer, sizeof(buffer), "%s(%d)--cnt: %d", s.c_str(), self, number++);
        // // 发送信息给父进程
        // // strlen(buffer) 不需要 + 1 带上 \0，因为 \0 是 C/C++ 的语法规定
        // // wrtie 向管道文件写入，管道文件没有这个规定，只写入数据内容即可。
        write(wfd, buffer, strlen(buffer)); 
        // //sleep(1);

        // char ch = 'c';
        // write(wfd, s.c_str(), s.size());
        // number++;
        // cout << "写入数据：" << s.c_str() << "\n";
        // // 子进程退出
        // if(number >= 5) break;
    }
}

void Reader(int rfd)
{
    int cnt = 0;
    char buffer[M];
    while(1)
    {
        // read 返回实际读取的字符个数
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if(n > 0)
        {
            // 读取到的字符串没有带 \0, 因此补上。
            buffer[n] = '\0';
            cout << "father process(" << getpid() << ") get the message: " << buffer << endl;
        }
        else if(n == 0) break;  // 写端关闭后，读端读到文件尾后，不再继续读取
        else break;

        if(++cnt > 5) break;
        // TODO
        // cout << "读取的实际字符：" << n << '\n';
    }
}

int main()
{
    int pipefd[N];
    int n = pipe(pipefd);
    if (n < 0) return 1;
    // cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]: " << pipefd[1] << endl;

    // father->r, child->w
    // pipefd[0]: 读端下标	pipefd[1]: 写端下标
    pid_t id = fork();
    if (id < 0) return 2;
    else if (id == 0)
    {
        // child process
        close(pipefd[0]); // 子进程关闭读端的文件描述符

        Write(pipefd[1]); // 子进程写
        close(pipefd[1]);
        exit(0);
    }
    // father process
    close(pipefd[1]); // 父进程先关闭写端的文件描述符

    Reader(pipefd[0]);  // 父进程读5s
    close(pipefd[0]);   // 关闭读端
    cout << "father process close read fd: " << pipefd[0] << "\n";
    sleep(2);       // 观察子进程状态（僵尸）

    int status = 0;
    pid_t returnId = waitpid(id, &status, 0);   // 等待回收子进程
    if(returnId < 0) return 1;

    cout << "wait child process sucess: " << returnId << ", exit signal: " << (status & 0x7f) << ", exit code: " << ((status >> 8) & 0xff) << '\n';

    sleep(2);

    cout << "father process quit!\n";
    return 0;
}
